package com.groenlid.mobileapp.Utils;

import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.auth.BasicScheme;
import org.apache.http.impl.client.AbstractHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;

import com.groenlid.mobileapp.MobApp;

import android.app.AlertDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;

public class RestClient{
	private String username = "";
	private String password = "";
	private SharedPreferences prefs;
	
	/*
	 *  GLOBAL STUFF
	 */
	
	private Context c;
	
	/*
	 *  REST CLIENT URLS
	 * */
	public final String GHOST = "groenlid.com";
	public final String GVERIFY = "http://groenlid.com/div/mobileapi/user/verify";
	public final String GUSER = "http://groenlid.com/div/mobileapi/user/";
	
	
	
	public RestClient(Context c)
	{
		this.c = c;
	}
	
	public boolean isLoggedIn(SharedPreferences prefs)
	{
		String username = prefs.getString("username", "");
		String password = prefs.getString("password", "");
		if(username.length() == 0 || password.length() == 0)
			return false;
		return this.login(username, password, true);
	}
	
	public boolean login(String username, String password)
	{
		return this.login(username, password,true);
	}
	
	public boolean login(String username, String password, boolean keepCred)
	{
		if(keepCred)
		{
			this.username = username;
			this.password = password;
		}
		return this.executeRest(GVERIFY).getStatusLine().getStatusCode() == 200;
	}
	
	public HttpResponse executeRest(String url)
	{
		HttpClient client = new DefaultHttpClient();
		AuthScope as = new AuthScope(GHOST, 80);
		
		UsernamePasswordCredentials upc = new UsernamePasswordCredentials(username,password);
		((AbstractHttpClient) client).getCredentialsProvider().setCredentials(as, upc);
		BasicHttpContext localContext = new BasicHttpContext();
		
		BasicScheme basicAuth = new BasicScheme();
		localContext.setAttribute("preemtive-auth", basicAuth);
		
		HttpHost targetHost = new HttpHost(GHOST, 80, "http");
		
		HttpGet httpget = new HttpGet(url);
		
		HttpResponse response = null;
		try{
			response = client.execute(targetHost, httpget, localContext);
		}catch(Throwable e){
			Log.e(MobApp.TAG,"HttpResponse error: " + e);
			buggy(e);
		}
        
		return response;
	}
	
	public void buggy(Throwable bugString)
	{
		AlertDialog.Builder builder = new AlertDialog.Builder(c);
		
		builder.setTitle("Buggy!!")
		.setMessage(bugString.toString())
		.setPositiveButton("OK", null)
		.show();
	}
}
